package pers.xuyong.strive.datastruct.mode.single;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 懒汉式,线程不安全
 *
 * @author billymac
 * @version 1.0
 * @date 17/6/23  下午11:32
 * @since JDK1.8
 */
public class LazyModeSingleton {

    private static LazyModeSingleton lazyModeSingleton;

    private final static Lock lock = new ReentrantLock(false);

    private LazyModeSingleton() {}

    /**
     * 线程不安全
     * @return
     */
    public static LazyModeSingleton getLazyModeSingleton() {
        if(lazyModeSingleton == null)
            lazyModeSingleton = new LazyModeSingleton();
        return lazyModeSingleton;
    }

    /**
     * 线程安全,同步方法
     * @return
     */
    synchronized  public static LazyModeSingleton getLazyModeSingletonSync() {
        if (lazyModeSingleton == null)
            lazyModeSingleton = new LazyModeSingleton();
        return lazyModeSingleton;
    }

    /**
     * 线程安全
     * @return
     */
    public static LazyModeSingleton getLazyModeSingletonPartSync() {
        if (lazyModeSingleton == null)
            synchronized (LazyModeSingleton.class) {
                if (lazyModeSingleton == null)
                    lazyModeSingleton = new LazyModeSingleton();
            }

        return lazyModeSingleton;
    }

    /**
     * 线程安全
     * @return
     */
    public static LazyModeSingleton getLazyModeSingletonPartLock() {
        try {
            lock.lock();
            if (lazyModeSingleton == null)
                lazyModeSingleton = new LazyModeSingleton();
        } finally {
            lock.unlock();
        }
        return lazyModeSingleton;
    }

    public void display() {
        System.out.println(LazyModeSingleton.class.getName() + " is Lazy Mode Singleton!");
    }
}
